package com.jinniulive.platform.tools;

import android.app.Activity;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jinniulive.platform.MyApp;
import com.jinniulive.platform.bean.GetMicOrderAns;
import com.jinniulive.platform.bean.GetSysMessageAns;
import com.jinniulive.platform.bean.NormalChat;
import com.jinniulive.platform.bean.SocketInfo;
import com.jinniulive.platform.bean.UserListAns;
import com.jinniulive.platform.bean.loginAns;
import com.jinniulive.platform.module.live.LiveActivity;
import com.jinniulive.platform.urls.AgreementConfig;

import java.net.URISyntaxException;
import java.util.List;

import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;

/**
 * Created by Administrator on 2016/12/8.
 */

public class SocketUtil{


    private Socket mSocket;
    private MyApp mMyApp;
    private Boolean isConnected = false;
    private Activity mActivity;
    private UsersManage mUsersManage;

    {
        try {
            // mSocket = IO.socket("http://114.215.127.158:3000");
            mSocket = IO.socket("http://114.215.99.203:3003");

        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }


    public SocketUtil(MyApp myApp, Activity activitty) {
        mMyApp=myApp;
        mUsersManage=new UsersManage();
        mActivity = activitty;
        listener();

    }
    public void sendLogin(String roomId, String userID,String userPassword,String roomPassword){
        String format = String.format(AgreementConfig.ROOMLOGIN, roomId, userID, userID,userPassword, roomPassword);
        sendMessage(format);

    }
    public void sendChatMsg(String roomId, String userID,int msgType,int senderID,int receiverId,String chatMsg){
        String format = String.format(AgreementConfig.CHATMSG, roomId, userID, msgType, senderID, receiverId, chatMsg);
        Log.e( "sendChatMsg: ",format );
        sendMessage(format);
    }

    private void sendMessage(String s) {
        mSocket.emit("message", s);
    }

    public void listener() {
        //连接服务器
        mSocket.on(Socket.EVENT_CONNECT,onConnect);

        // 连接失败 检查网络
        mSocket.on(Socket.EVENT_DISCONNECT,onDisconnect);
        //连接错误监听 连接失败
        mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
        //连接超时监听  连接失败
        mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
        //接受监听
        mSocket.on("message", onMessage);
        //连接
        mSocket.connect();
    }

    private Emitter.Listener onConnect =new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (!isConnected){
                        isConnected=true;
                        Toast.makeText(mActivity, "已连接", Toast.LENGTH_SHORT).show();
                    }
                }
            });

        }
    };

    private Emitter.Listener onDisconnect =new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (!isConnected){
                        Toast.makeText(mActivity, "请检查网络", Toast.LENGTH_SHORT).show();
                        isConnected=false;
                    }
                }
            });
        }
    };

    private Emitter.Listener onConnectError =new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (!isConnected){
                        Toast.makeText(mActivity, "连接失败", Toast.LENGTH_SHORT).show();
                        isConnected = false;
                    }
                }
            });
        }
    };

    public Emitter.Listener onMessage = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            mActivity.runOnUiThread(new Runnable() {


                @Override
                public void run() {
                    String result = args[0].toString();
                    Log.e( "run: ", result);
                    Gson gson=new Gson();
                    SocketInfo socketInfo = gson.fromJson(result, SocketInfo.class);
                    int cmd = socketInfo.getHead().getCmd();
                    if (cmd!=0){
                        switch (cmd){
                            case 63://登陆
                                loginAns loginAns = gson.fromJson(result, loginAns.class);
                                int errorCode = loginAns.getContent().getErrorCode();
                                if (errorCode == 0){
                                    ((LiveActivity) mActivity).stopAnimation();
                                    Toast.makeText(mActivity, "连接成功", Toast.LENGTH_SHORT).show();
                                }else {
                                    Toast.makeText(mActivity, "进入失败", Toast.LENGTH_SHORT).show();
                                    ((LiveActivity) mActivity).finish();
                                }
                                break;
                            case 55://视频地址 nickName
                                GetMicOrderAns getMicOrderAns = gson.fromJson(result, GetMicOrderAns.class);
                                String rtmpURL = getMicOrderAns.getContent().getRtmpURL();
                                String nickName = getMicOrderAns.getContent().getNickName();
                                ((LiveActivity) mActivity).player(rtmpURL);
                                ((LiveActivity) mActivity).setInfo(nickName);
                                break;
                            case 59://主题
                                GetSysMessageAns getSysMessageAns = gson.fromJson(result, GetSysMessageAns.class);
                                String mMsg = getSysMessageAns.getContent().getMsg();
                                int mMsgType = getSysMessageAns.getContent().getMsgType();
                                switch (mMsgType){
                                    case 1:
                                        mMsg="房间主题："+mMsg;
                                        break;
                                    case 2:
                                        mMsg="房间公告："+mMsg;
                                        break;
                                    case 3:
                                        mMsg="广告："+mMsg;
                                        break;
                                    default:
                                        break;
                                }
                                ((LiveActivity) mActivity).showHtml(mMsg,3);
                                break;
                            case 74://用户信息
                                UserListAns userListAns = gson.fromJson(result, UserListAns.class);
                                List<UserListAns.ContentBean.UserListBean> userList = userListAns.getContent().getUserList();
                                for (int i = 0; i < userList.size(); i++) {
                                    UserListAns.ContentBean.UserListBean listBean = userList.get(i);
                                    //用户类赋值
                                    if (listBean.getNickName()!=null){
                                        mUsersManage.AddUsers(listBean.getUserID(),listBean.getNickName(),listBean.getUserLevel(),
                                                listBean.getFaceIndex(),listBean.getMngLevel(),listBean.getMicState());
                                    }

                                    //管理级别
                                    int mngLevel = userList.get(i).getMngLevel();
                                    if (mngLevel>0){
                                        String nickName1 = userList.get(i).getNickName();
                                        int userID = userList.get(i).getUserID();
                                        ((LiveActivity) mActivity).setUserList(userID);

                                    }

                                }
                                break;
                            case 73:
//                                UserListAns userListAns2 = gson.fromJson(result, UserListAns.class);
//                                List<UserListAns.ContentBean.UserListBean> userList1 = userListAns2.getContent().getUserList();
//                                for (int i = 0; i < userList1.size(); i++) {
//                                    UserListAns.ContentBean.UserListBean bean = userList1.get(i);
//                                    mUsersManage.AddUsers(bean.getUserID(),bean.getNickName(),bean.getUserLevel(),
//                                            bean.getFaceIndex(),bean.getMngLevel(),bean.getMicState());

//                                }

                                break;
                            //接受聊天
                            case 166:
                                NormalChat normalChat = gson.fromJson(result, NormalChat.class);
                                String chatMsg = normalChat.getContent().getChatMsg();
                                int msgType = normalChat.getContent().getMsgType();
                                int receiverID = normalChat.getContent().getReceiverID();
                                int senderID = normalChat.getContent().getSenderID();
                                int itype=0;

                                int userID = mMyApp.getLoginInfo().getUserslist().get(0).getUserID();
                                Log.e( "run: ", userID+"");
                                if (senderID== userID){
                                    itype=1;
                                }else if (receiverID== userID){
                                    itype=2;
                                }
                                String html = "";
                                switch (msgType){
                                    //公聊
                                    case 1:
                                        html=HtmlFormat.FormatPublicChat(senderID,
                                                mUsersManage.GetUserNickName(senderID),receiverID,mUsersManage.GetUserNickName(receiverID),
                                                chatMsg,itype);
                                        ((LiveActivity) mActivity).showHtml(html,1);
                                        if (itype==1){
                                            ((LiveActivity) mActivity).showHtml(html,2);
                                        }
                                        break;
                                    case 2:
                                        html=HtmlFormat.FormatPublicChatToAll(senderID,mUsersManage.GetUserNickName(senderID),chatMsg,itype);
                                        ((LiveActivity) mActivity).showHtml(html,1);
                                        if (itype==1){
                                            ((LiveActivity) mActivity).showHtml(html,2);
                                        }

                                        break;
                                    case 3:
                                        html=HtmlFormat.FormatPublicChatToAll(senderID,mUsersManage.GetUserNickName(senderID),chatMsg,itype);
                                        ((LiveActivity) mActivity).showHtml(html,1);
                                        if (itype==1){
                                            ((LiveActivity) mActivity).showHtml(html,2);
                                        }
                                        break;

                                    case 4:

                                        break;

                                }

                                break;


                        }
                    }
                }
            });

        }
    };

    public void offSocket(){
        mSocket.disconnect();
        mSocket.off(Socket.EVENT_CONNECT,onConnect);
        mSocket.off(Socket.EVENT_DISCONNECT,onDisconnect);
        //连接错误监听 连接失败
        mSocket.off(Socket.EVENT_CONNECT_ERROR, onConnectError);
        //连接超时监听  连接失败
        mSocket.off(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
        mSocket.off("message", onMessage);
    }

}
